//
//  JXLUserAccount.swift
//  MicroBlog
//
//  Created by 贾晓磊 on 16/9/23.
//  Copyright © 2016年 贾晓磊. All rights reserved.
//

import UIKit

private let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archiver")

class JXLUserAccount: NSObject, NSCoding {

    //用户唯一标识
    var access_token: String?
    //access_token的生命周期，单位是秒数
    var expires_in: TimeInterval = 0 {
        didSet {
           
            expiresDate = Date().addingTimeInterval(expires_in)
        }
    }
    //过期时间
    var expiresDate: Date?
    //授权用户的uid
    var uid: Int64 = 0
    //用户名
    var name: String?
    //用户头像
    var avatar_large: String?
    // MARK: 方法＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝
    
    //kvc 构造函数
    init(dict: [String: Any]) {
        super.init()
        setValuesForKeys(dict)
    }
    
    //防止kcv构造函数崩溃
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        //print("不存在的key->\(key)")
    }
    //归档与解档
     func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expiresDate, forKey: "expiresDate")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
    }
    
    required init?(coder aDecoder: NSCoder) {
       access_token = aDecoder.decodeObject(forKey: "access_token") as? String
       expiresDate = aDecoder.decodeObject(forKey: "expiresDate") as? Date
        uid = aDecoder.decodeInt64(forKey: "uid")
        name = aDecoder.decodeObject(forKey: "name") as? String
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
    }
    
    //保存当前用户对象
    func saveUserAccount() -> Void {
        
        
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
    //读取当前用户对象
   class func loadUserAccount() -> JXLUserAccount? {
       
        return NSKeyedUnarchiver.unarchiveObject(withFile: path) as? JXLUserAccount
    }
}
